import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:process_run/shell.dart';

import '../val/args_val.dart';
import 'basic_shell.dart';

class TimerCommand extends BasicShell {
  var shell = Shell(runInShell: true);

  final Function callbackExit;

  TimerCommand(super.args, this.callbackExit);

  @override
  Future doExecute() async {
    // 定义要进入的目录和要执行的脚本
    String argPath = args[ArgsVal.project];

    String scriptName = 'self.sh';

    String destDirectory = argPath;
    String destDir = "$destDirectory/sh";

    // 检查脚本是否存在
    File scriptFile = File('$destDir/$scriptName');
    if (!scriptFile.existsSync()) {
      print('脚本文件不存在: $scriptName');
      return;
    }

    // 检查脚本是否有执行权限
    int auth = (scriptFile.statSync().mode & 0x111);
    if (auth != 257) {
      print('脚本没有执行权限，正在尝试添加执行权限...');
      try {
        await shell.run('chmod +x $destDir/$scriptName');
        print('已成功添加执行权限');
      } catch (e) {
        print('添加执行权限失败: $e');
        return;
      }
    }
    var random = Random();

    DateTime time = DateTime.now();
    await _executeTask(destDir, scriptName, time);

    Timer.periodic(Duration(minutes: 1 + random.nextInt(3 - 1)), (timer) async {
      DateTime timeTask = DateTime.now();
      await _executeTask(destDir, scriptName, timeTask);
    });
    return;
  }

  _executeTask(String destDir, String scriptName, DateTime time) async {
    print('当前时间：${time.hour} : ${time.minute} : ${time.second}');
    if (time.hour == 19) {
      print('19点，退出程序');
      callbackExit.call();
    }
    if (time.hour != 12) {
      try {
        // 设置工作目录
        shell = shell.cd(destDir);
        // 执行脚本
        var result = await shell.run('./$scriptName');

        print('命令执行成功：');
      } catch (e) {
        print('执行命令时出错：$e');
      }
    }
  }
}
